'use strict';

const { Service } = require('egg');

class KujoMiva extends Service {
    async login(option) {
        const result = await this.app.mysql.get('user', option);
        // 如果用户不存在
        if (result === null) {
            return { status: 404, token: null, message: '用户不存在' };
        }

        const { id: user_id, password } = result;
        const token = await this.app.encodeToken_login({ user_id });

        return { status: 200, token, message: '登录成功', user_id, password };
    }

    async register(option) {
        const returnBody = { status: 200, token: null, message: '注册成功' };
        return await this.app.mysql.beginTransactionScope(async conn => {
            // 注册操作
            const { insertId } = await conn.insert('user', option);
            // 创建角色操作
            await conn.insert('user_info', {
                user_id: insertId,
                nickname: `萌新${this.app.createNum(4)}`
            });
            // 包装token
            returnBody.token = await this.app.encodeToken_login({ user_id: insertId });
            return insertId;
        }, this.ctx)
            .then(async res => {
                console.log(res);
                return returnBody;
            })
            .catch(err => {
                console.log(err);
                return { status: 400, token: null, message: '用户已存在' };
            });
    }
}

module.exports = KujoMiva;
